package com.freeheart.filterorder;

import jakarta.servlet.Filter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.annotation.OrderUtils;

/**
 * 在FilterRegistrationBean(注册Filter的Bean)的属性配置完毕以后，我们在postProcessAfterInitialization方法中
 * 修改里面的order属性，来达到识别Order的目标
 */
public class FilterOrderConfig implements BeanPostProcessor {


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        if (bean instanceof FilterRegistrationBean<?> filterRegistrationBean) {
            Filter filter = filterRegistrationBean.getFilter();
            int order = getOrder(filter);
            filterRegistrationBean.setOrder(order);
        }

        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    /**
     * 获取Filter的order:支持Ordered接口、@Order注解，当同时出现时，以Ordered接口为准，如果没有，则使用默认值Integer.MAX_VALUE
     *
     * @param filter Servlet中提供的过滤器
     * @return order
     */
    private int getOrder(Filter filter) {
        int order = Ordered.LOWEST_PRECEDENCE;
        if (filter instanceof Ordered ordered) {
            order = ordered.getOrder();
        } else if (filter.getClass().getAnnotation(Order.class) != null) {
            order = OrderUtils.getOrder(filter.getClass());
        }
        return order;
    }
}
